package org.bb.es.heighlevel.runner;

import com.google.gson.Gson;
import org.apache.http.entity.ContentType;
import org.apache.http.nio.entity.NStringEntity;
import org.bb.es.heighlevel.config.EsHighLevelClient;
import org.bb.es.heighlevel.config.EsRestHighLevelClientConfig;
import org.bb.es.heighlevel.model.Product;
import org.bb.es.heighlevel.service.ProductService;
import org.elasticsearch.ElasticsearchStatusException;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.common.xcontent.json.JsonXContent;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class InitDataRunner implements CommandLineRunner, EsRestHighLevelClientConfig {

    private final ProductService productService;

    public InitDataRunner(ProductService productService) {
        this.productService = productService;
    }

    @Override
    @EsHighLevelClient
    public void run(String... args) throws Exception {

        Boolean reslult = false;
        DeleteIndexRequest request = new DeleteIndexRequest("my_index");
        try {
            AcknowledgedResponse response = TH_CLIENT.get().indices().delete(request, RequestOptions.DEFAULT);
            if (response.isAcknowledged()) {
                reslult = true;
            }
        } catch (ElasticsearchStatusException e) {
            reslult = true;
        }

        if (reslult) {
            System.out.println("删除 index 成功");

            IndexRequest indexRequest = new IndexRequest();
            XContentBuilder builder = JsonXContent.contentBuilder()
                    .startObject()
                        .startObject("mappings")
                            .startObject("doc")
                                .startObject("properties")
                                    .startObject("name")
                                        .field("type", "text")
                                        .field("analyzer", "ik_max_word")
                                    .endObject()
                                    .startObject("producer")
                                        .field("type", "text")
                                        .field("analyzer", "ik_max_word")
                                    .endObject()
                                    .startObject("price")
                                        .field("type", "long")
                                    .endObject()
                                .endObject()
                            .endObject()
                        .endObject()
                        .startObject("settings")
                            .field("number_of_shards", 3)
                            .field("number_of_replicas", 2)
                        .endObject()
                    .endObject();

            indexRequest.source(builder);

            // 生成 json 字符串
            String source = indexRequest.source().utf8ToString();
            NStringEntity entity = new NStringEntity(source, ContentType.APPLICATION_JSON);

            BulkRequest bulkRequest = new BulkRequest("my_index");
            Gson gson = new Gson();
            List<Product> list = productService.list();
            list.forEach(product -> {
                bulkRequest.add(new IndexRequest().source(gson.toJson(product), XContentType.JSON));
            });
            BulkResponse bulkResponse = TH_CLIENT.get().bulk(bulkRequest, RequestOptions.DEFAULT);
            System.out.println("数量：" + bulkResponse.getItems().length);

        } else {
            System.out.println("删除 index 失败!");
        }
    }
}
